package com.ideabove.heart;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.ideabove.heart.R;
import com.ideabove.heart.manager.AppManager;
import com.ideabove.heart.manager.ScheduleManager;

import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;

import net.simonvt.app.TimePickerDialog;
import net.simonvt.widget.TimePicker;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PorterDuff.Mode;

public class AlarmSetActivity extends MyActivity {

	DateFormat formatDateTime=DateFormat.getDateTimeInstance();
	public Calendar dateTime=Calendar.getInstance();
	private boolean isAlarmOn = true;	
	TimePicker settedTimePicker;
	
	static final int TIME_DIALOG_ID = 999;
	
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.alarm_set);
		
		AppManager.start();
				
		// 시간클릭
		TextView clock_time_txt = (TextView) findViewById(R.id.clock_time_txt);
		
		// 현재 시간 입력
		SimpleDateFormat fmt = new SimpleDateFormat("HH:mm");
		Date date = new Date();
		String dateString = fmt.format(date);
		
		clock_time_txt.setText(dateString);
		clock_time_txt.setOnTouchListener(new View.OnTouchListener() {			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub				
				showDialog(TIME_DIALOG_ID);
				return false;
			}
		});
		
		// 5번반복
		ImageView alarm_repeat_img = (ImageView) findViewById(R.id.alarm_repeat_img);
		alarm_repeat_img.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {				
				// TODO Auto-generated method stub
				ImageView view = (ImageView)v;
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					view.setPadding(2, 2, 2, 2);
					view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
				}else if(event.getAction() == MotionEvent.ACTION_UP){
					DialogRepeatCount();

					view.setPadding(0, 0, 0, 0);
					view.setColorFilter(0x00000000, Mode.SRC_OVER);
				}else{
					view.setPadding(0, 0, 0, 0);
					view.setColorFilter(0x00000000, Mode.SRC_OVER);
				}
				return true;
			}
		});
		
		// 온버튼 누를때
		ImageView alarm_btn_on = (ImageView) findViewById(R.id.alarm_btn_on);
		alarm_btn_on.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {				
				// TODO Auto-generated method stub
				ImageView view = (ImageView)v;
				view.setImageResource(getResources().getIdentifier("clock_on_red", "drawable", getPackageName()));
				
				ImageView alarm_btn_off = (ImageView) findViewById(R.id.alarm_btn_off);
				alarm_btn_off.setImageResource(getResources().getIdentifier("clock_off_gray", "drawable", getPackageName()));
				
				isAlarmOn = true;
				return true;
			}
		});
		
		// off 버튼 누를때		
		ImageView alarm_btn_off = (ImageView) findViewById(R.id.alarm_btn_off);
		alarm_btn_off.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {				
				// TODO Auto-generated method stub
				ImageView view = (ImageView)v;
				view.setImageResource(getResources().getIdentifier("clock_off_red", "drawable", getPackageName()));
				
				ImageView alarm_btn_on = (ImageView) findViewById(R.id.alarm_btn_on);		
				alarm_btn_on.setImageResource(getResources().getIdentifier("clock_on_gray", "drawable", getPackageName()));	
					
				isAlarmOn = false;
				return true;
			}
		});
		
		// 확인
		ImageView confirm = (ImageView)findViewById(R.id.alarmset_btn);				
		confirm.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				ImageView view = (ImageView)v;
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					view.setPadding(2, 2, 2, 2);
					view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
				}else if(event.getAction() == MotionEvent.ACTION_UP){
					setAlarm();

					view.setPadding(0, 0, 0, 0);
					view.setColorFilter(0x00000000, Mode.SRC_OVER);
				}else{
					view.setPadding(0, 0, 0, 0);
					view.setColorFilter(0x00000000, Mode.SRC_OVER);
				}
				return true;
			}
		});		
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case TIME_DIALOG_ID:
			// set time picker as current time			
			Calendar rightNow = Calendar.getInstance();// 날짜 불러오는 함수			
			TimePickerDialog dialog =  new TimePickerDialog(this, 
                                        timePickerListener, 
                                        rightNow.get(Calendar.HOUR_OF_DAY), 
                                        rightNow.get(Calendar.MINUTE),
                                        true);

			dialog.setTitle("알람설정");
			return dialog;
		}
		return null;
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		finish();
	}
	
	private TimePickerDialog.OnTimeSetListener timePickerListener = 
        new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker timePicker, int selectedHour,
				int selectedMinute) {
			
			settedTimePicker = timePicker;
			
			TextView clock_time_txt = (TextView) findViewById(R.id.clock_time_txt);
			
			// 현재 시간 입력			
			Calendar show = Calendar.getInstance();
			show.set(Calendar.HOUR_OF_DAY, settedTimePicker.getCurrentHour());
			show.set(Calendar.MINUTE,	settedTimePicker.getCurrentMinute());
			
			SimpleDateFormat fmt = new SimpleDateFormat("HH:mm");
			Date date = new Date(show.getTimeInMillis());
			String dateString = fmt.format(date);
			clock_time_txt.setText(dateString);
			
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + 1);
			calendar.set(Calendar.HOUR_OF_DAY, settedTimePicker.getCurrentHour());
			calendar.set(Calendar.MINUTE,	settedTimePicker.getCurrentMinute());
			calendar.set(Calendar.SECOND, 0);
			
			Date notiDate = new Date( calendar.getTimeInMillis());
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyy년MM월dd일 HH시mm분"); 
	        String strResult = sdf.format( notiDate );	        	        
	        
	        AlertDialog.Builder ab=new AlertDialog.Builder(AlarmSetActivity.this);
			ab.setMessage(strResult +"에 모닝콜이 오겠군.\n지금 진동모드는 아니겠지?");			
			ab.setPositiveButton("확인", null);
			ab.show();
		}
	};	
	
	private void setAlarm(){	
		if(isAlarmOn){ // 알람온
			if(settedTimePicker == null){
				Toast.makeText(this, "시간을 눌러 알람을 세팅해주세요.", Toast.LENGTH_SHORT).show();
				return;
			}
		
			ImageView repeatCnt = (ImageView)findViewById(R.id.alarm_repeat_img);
			
			int repeat = Integer.parseInt(repeatCnt.getContentDescription().toString());
			int intervalTime = 5;
			
			if(repeat == 0){
				intervalTime = 0;
			}			
			dateTime.set(Calendar.DAY_OF_YEAR, dateTime.get(Calendar.DAY_OF_YEAR) + 1);
			dateTime.set(Calendar.HOUR_OF_DAY, settedTimePicker.getCurrentHour());
			dateTime.set(Calendar.MINUTE,	settedTimePicker.getCurrentMinute());
			dateTime.set(Calendar.SECOND, 0);
			
			final int isUse = (isAlarmOn == true) ? 1 : 0;
			
			ScheduleManager scheMgr = new ScheduleManager(AlarmSetActivity.this);			
	        // 알람세팅
	        scheMgr.resetAlarm(
	       		 1,
	       		 settedTimePicker.getCurrentHour(),
	       		 settedTimePicker.getCurrentMinute(),
	   			 dateTime.getTimeInMillis(),
	   			 isUse,
	   			 intervalTime,
	   			 repeat);
	        scheMgr.alarmSetDone(dateTime.getTimeInMillis());
	        
		}else{ // 알람오프			
			final int isUse = (isAlarmOn == true) ? 1 : 0;
			
			ScheduleManager scheMgr = new ScheduleManager(AlarmSetActivity.this);
			ScheduleManager.unregisterAlarm(AlarmSetActivity.this);
			
	        // 알람세팅
	        scheMgr.resetAlarm(
	       		 1,
	       		 0,
	       		 0,
	   			 dateTime.getTimeInMillis(),
	   			 isUse,
	   			 1,
	   			 0); 
	        scheMgr.alarmSetDone(dateTime.getTimeInMillis());
		}				
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		AppManager.pause(AlarmSetActivity.this);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub		
		super.onDestroy();
	}

	private void DialogRepeatCount() {
		final String items[] = { "0번 반복","1번 반복","2번 반복"};
		final String repeatImgs[] = { "clock_repeat0","clock_repeat1","clock_repeat2"};
		final String intervalImgs[] = { "clock_interval_on","clock_interval_off"};
		AlertDialog.Builder ab = new AlertDialog.Builder(AlarmSetActivity.this);
		ab.setTitle("반복 횟수");
		ab.setSingleChoiceItems(items, 0,
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				
				// 반복 횟수
				ImageView alarm_repeat_img = (ImageView)findViewById(R.id.alarm_repeat_img);
				alarm_repeat_img.setImageResource(getResources().getIdentifier(repeatImgs[whichButton], "drawable", getPackageName()));
				alarm_repeat_img.setContentDescription(String.valueOf(whichButton));
				
				// 5분간격
				
				if(whichButton > 0){
					ImageView alarm_interval_img = (ImageView)findViewById(R.id.alarm_interval_img);
					alarm_interval_img.setImageResource(getResources().getIdentifier(intervalImgs[0], "drawable", getPackageName()));
				}else{
					ImageView alarm_interval_img = (ImageView)findViewById(R.id.alarm_interval_img);
					alarm_interval_img.setImageResource(getResources().getIdentifier(intervalImgs[1], "drawable", getPackageName()));
				}
			}
		}).setPositiveButton("Ok",
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		}).setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		});
		ab.show();
	}



	@Override
	protected void onNewIntent(Intent intent) {		

		super.onNewIntent(intent);
		setIntent(intent);
	}
//
//	TimePickerDialog.OnTimeSetListener t=new TimePickerDialog.OnTimeSetListener() {
//
//		@Override
//		public void onTimeSet(net.simonvt.widget.TimePicker view,
//				int hourOfDay, int minute) {
//			// TODO Auto-generated method stub
//			dateTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
//			dateTime.set(Calendar.MINUTE,minute);
//			dateTime.set(Calendar.SECOND, 0);
//
//
//			Intent iAlarm = new Intent(AlarmSetActivity.this, MoeIntroActivity.class);
//			iAlarm.addFlags(Intent.FLAG_FROM_BACKGROUND);
//			iAlarm.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);   // Added
//			iAlarm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);              
//			iAlarm.putExtra("settime", "" + dateTime.getTimeInMillis()); 
//
//
//			startActivity(iAlarm);   
//
//			//			setContentView(R.layout.activity_main);  
//
//			//			updateAlarm();
//		}
//	};
//
//
//	private void updateAlarm() {		
//		timeLabel.setText(formatDateTime.format(dateTime.getTime()));
//
//		AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//		Intent intent = new Intent(this, AlarmReceiver.class);
//
//		Date today = new Date();
//		today.setTime(dateTime.getTimeInMillis());
//
//		PendingIntent sender = PendingIntent.getBroadcast(
//				this, 1234, intent, PendingIntent.FLAG_CANCEL_CURRENT);
//		//      am.setInexactRepeating(AlarmManager.RTC_WAKEUP, dateTime.getTimeInMillis(), 1, pendingIntent);
//
//		am.set(
//				AlarmManager.ELAPSED_REALTIME,
//				dateTime.getTimeInMillis(),
//				sender
//				);
//
//		am.setRepeating(
//				AlarmManager.RTC_WAKEUP,
//				dateTime.getTimeInMillis(),
//				AlarmManager.INTERVAL_DAY,sender
//				);
//
//	}

	
}
